<?php

namespace app\member\model;

use Db;
use think\Model;

class Member extends Model
{
    protected $table              = 'tp_user';
    protected $autoWriteTimestamp = true;
    //protected $insert             = ['status' => 1, 'tid' => 1];
    protected $update = ['tid' => 2]; //后台用户

    protected function setUserNameAttr($value)
    {
        return trim($value);
    }
    protected function setNicknameAttr($value)
    {
        return trim($value);
    }

    protected function setEmailAttr($value)
    {
        return trim($value);
    }

    protected function setPasswordAttr($value)
    {
        return self::editpassword($value);
    }

    public static function listpage($value = '')
    {
        return self::paginate(10);
    }

    /**
     * 会员注册
     * @param  [type] $post 传入表单数据
     * @return [type]       [description]
     */
    public static function register($post)
    {
        if (!empty($post)) {
            $user = self::create([
                'user_name' => $post['user'],
                'password'  => $post['password'],
                'email'     => $post['email'],
                'tid'       => 2,
                'status'    => 0,
            ]);
            if ($user->id > 0) {
                return true;
            }
        }
    }
    /**
     * 找回密码生成找回密码连接
     * @param  [type] $post 传入表单数据
     * @return [type]       [description]
     */
    public static function resetpwd($post)
    {
        if (!empty($post)) {
            $user = self::where([
                ['tid', '=', 2],
                ['user_name', '=', $post['user']],
                ['email', '=', $post['email']],
            ])->find();
            if (!empty($user)) {

                $token = md5($user['id'] . $user['user_name'] . $user['password']); //同时我们为了控制URL链接的时效性
                $link  = \Request::domain() . '/' . url('login/pwdtoken', ['email' => $user['email'], 'token' => $token]);
                //$str        = "您好!{$user['user_name']}， 请点击下面的链接重置您的密码：<p></p>" . $link;

                $str = "尊敬的{$user['user_name']}先生/女士：<br />    取回密码邮件<br />请点击下面的链接，按流程进行密码重设。<a href=\"{$link}\" mce_href=\"{$link}\">{$link}</a><br><h4>有效期30分钟</h4>(如果上面不是链接形式，请将地址手工粘贴到浏览器地址栏再访问)上面的页面打开后，输入新的密码后提交，之后您即可使用新的密码登录了。<br><br>此邮件为系统邮件，请勿直接回复";

                $sendResult = sendEmail($user['email'], $str, "密码找回", '网站密码找回');

                if (!$sendResult) {
                    exit($sendResult->ErrorInfo);
                }
                //修改密码发送时间
                $passwordTime = time();
                $updateResult = self::where([['tid', '=', 2], ['id', '=', $user['id']]])->setField('pwdtime', $passwordTime);
                if (!$updateResult) {
                    exit('修改数据库密码发送时间失败！');
                }
                return true;
            }
        }
    }

    public static function edit($post, $id = '0')
    {
        if ($id != 0 && !empty($post)) {
            $data = self::get($id);
            if (trim($post['password'])) {
                $data->password = $post['password'];
            }
            $data->nickname = $post['nickname'];
            $data->email    = $post['email'];
            $data->sex      = $post['sex'];
            $data->remark   = $post['remark'];

            if ($data->save() > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    /*
    登录数据处理
     */
    public static function login($username, $password)
    {
        $data = self::where('status', 1)->where('tid', 2)->where('user_name', $username)->find(); //tid 为 1的后台用户
        if (!empty($data) && $data['password'] === self::editpassword($password)) {
            //设置session,cookie
            session('userid', $data['id']);
            cookie('username', $data['user_name']);
            cookie('uid', $data['id']);
            if (!empty($data['nickname'])) {
                cookie('nickname', $data['nickname']);
            }
            cookie('write', $data['nickname'] ? $data['nickname'] : $data['user_name']);

            $login_time = config('webconfig.login_time'); //配制文件中不存在时读取数据库
            if (!isset($login_time)) {
                $login_time = Db::name('webconfig')->where(['varname' => 'login_time'])->value('value');
            }

            $user_token = self::createToken($data['id'], 1, $login_time);
            session('user_token', $user_token);
            //更新状态
            self::where(['id' => $data['id']])->update(['login_ip' => request()->ip(), 'login_time' => time()]);
            return true;
        }
        return false;
    }

    /**
     * 用户密码添加干扰字符串
     * @param   $password      要加的字符串
     * @param   $password_code 干扰参数
     * @return                 返回加密后的字符串
     */
    public static function editpassword($password, $password_code = 'lshi4AsSUrUOwWV')
    {
        return md5(md5($password) . md5($password_code));
    }

    /**
     * @Title: createToken
     * @Description: todo(登陆时生成用户token)
     * @param int $uid 用户id
     * @param int $type 类型【1、PC，2、移动端】
     * @param int $token_time token令牌时限【PC登陆超时】
     * @return string
     * @date 2017年9月16日
     * @throws
     */
    public static function createToken($uid, $type = '1', $token_time = '')
    {
        $token      = md5($uid . uniqid() . rand(100000000, 999999999));
        $token_time = time() + $token_time;
        $where      = [
            'uid'  => $uid,
            'type' => $type,
        ];
        $isToken = Db::name('token_user')->where($where)->find();
        if (!empty($isToken)) {
            //存在token
            $data = [
                'token'       => $token,
                'token_time'  => $token_time,
                'update_time' => time(),
            ];
            Db::name('token_user')->where($where)->update($data);
        } else {
            $data = [
                'uid'         => $uid,
                'type'        => $type,
                'token'       => $token,
                'token_time'  => $token_time,
                'update_time' => time(),
            ];
            Db::name('token_user')->data($data)->insert();
        }
        return $token;
    }

    //
}
